package com.ysd.service.gateway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import com.ysd.service.entity.Weather;
import com.ysd.service.entity.WeatherInfo;
import com.ysd.service.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WeatherAPIClient {

    // 每分钟20次 => 换算成 每秒 ~ 0.333次
    private final RateLimiter minuteLimiter = RateLimiter.create(20.0 / 60.0);

    // 每小时400次 => 换算成 每秒 ~ 0.111次
    private final RateLimiter hourLimiter = RateLimiter.create(400.0 / 3600.0);

    // 心知天气API示例：当前天气
    // https://api.seniverse.com/v3/weather/now.json?key=YOUR_KEY&location=beijing&language=zh-Hans&unit=c
    private static final String WEATHER_URL = "https://api.seniverse.com/v3/weather/daily.json";

    // 你从心知天气官网申请的key
    private static final String API_KEY = "SEgB2j38xAPPH-mqa";

    @Autowired
    private WeatherService weatherService;

    // 如果需要在此类使用同一个 RestTemplate，可将其定义为 bean 或直接 new
    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取指定城市的实时天气，并保存到数据库
     *
     * @param cityName 如 "beijing" / "shanghai" / "shenzhen"
     */
    public void fetchAndSaveWeather(String cityName) throws IOException {
        // 1) 先从两个限流器获取许可
        minuteLimiter.acquire();
        hourLimiter.acquire();

        // 2) 构造请求URL
        //   ?key=API_KEY &location=cityName &language=zh-Hans &unit=c
        // 构建带查询参数的URL，让Spring自动做正确的编码
        String baseUrl = "https://api.seniverse.com/v3/weather/daily.json" +
                "?key={key}&location={city}&language=zh-Hans&unit=c";

        Map<String, String> uriVars = new HashMap<>();
        uriVars.put("key", API_KEY);
        uriVars.put("city", cityName);

        String respBody = restTemplate.getForObject(baseUrl, String.class, uriVars);

        // 3) 使用 RestTemplate 发起 GET 请求
        log.info("weather url response = " + respBody);
        if (respBody == null) {
            throw new IOException("获取天气返回为空，请检查请求URL或网络状态");
        }

        // 4) 解析并存储
        saveWeatherToDB(respBody);
    }

    // 保存天气数据
    private void saveWeatherToDB(String data) {
        log.info("saveWeatherToDB.param = " + data);

        // 1) 整体解析
        JSONObject jsonObject = JSONObject.parseObject(data);

        // 2) "results" 是一个数组
        JSONArray resultsArray = jsonObject.getJSONArray("results");
        if (resultsArray == null || resultsArray.isEmpty()) {
            System.err.println("API返回的 results 为空，无法解析");
            return;
        }
        JSONObject result = resultsArray.getJSONObject(0); // 取第一个
        JSONObject locationObj = result.getJSONObject("location");
        List<WeatherInfo> weatherInfoList = JSONArray.parseArray(result.getString("daily"), WeatherInfo.class);
        String lastUpdate = result.getString("last_update");

        weatherInfoList.forEach(e -> {

            // 3) 组装 Weather 对象(或你自己的实体)
            Weather weather = new Weather();
            weather.setLocationId(locationObj.getString("id"));
            weather.setLocationName(locationObj.getString("name"));
            weather.setLocationCountry(locationObj.getString("country"));
            weather.setLocationPath(locationObj.getString("path"));
            weather.setLocationTimezone(locationObj.getString("timezone"));
            weather.setLocationTimezoneOffset(locationObj.getString("timezone_offset"));
            weather.setLastUpdate(lastUpdate);

            // 封装天气信息，一天生成一条数据
            weather.setWeatherDate(e.getDate());
            weather.setWeatherInfo(JSON.toJSONString(e));

            // 插入天气信息数据
            weatherService.save(weather);
        });
    }


}
